package com.pengpeng.flash.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pengpeng.flash.common.BaseContext;
import com.pengpeng.flash.common.R;
import com.pengpeng.flash.dto.OrdersDto;
import com.pengpeng.flash.entity.Dish;
import com.pengpeng.flash.entity.OrderDetail;
import com.pengpeng.flash.entity.Orders;
import com.pengpeng.flash.entity.ShoppingCart;
import com.pengpeng.flash.service.OrderDetailService;
import com.pengpeng.flash.service.OrderService;
import com.pengpeng.flash.service.ShoppingCartService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> addOrder(@RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("订单提交成功");
    }

    /**
     * 订单管理
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    @Transactional
    public R<Page> orderPage(int page,int pageSize){
        //构造分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        Page<OrdersDto> ordersDtoPage = new Page<>();

        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //进行分页查询
        orderService.page(pageInfo,queryWrapper);

        //分页基础数据拷贝
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");

        List<Orders> records=pageInfo.getRecords();

        List<OrdersDto> list = records.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            //订单对象的基础数据拷贝
            BeanUtils.copyProperties(item, ordersDto);
            //根据订单id查分类对象
            Orders orders = orderService.getById(item.getId());
            //获取订单对象的订单号
            String number = orders.getNumber();
            //根据订单号查询出订单明细
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId,number);
            List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);

            //定义一个num变量表示订单中总共的数量，循环遍历每一个订单明细对象，获取他的数量+=给num
            int num=0;
            for(OrderDetail l:orderDetailList){
                num+=l.getNumber().intValue();
            }
            ordersDto.setSumNum(num);
            return ordersDto;
        }).collect(Collectors.toList());

        //设置核心数据
        ordersDtoPage.setRecords(list);

        return R.success(ordersDtoPage);
    }


    /**
     * 再来一单
     * @param order
     * @return
     */
    @PostMapping("/again")
    @Transactional
    public R<String> again(@RequestBody Orders order){
        //取得orderId
        Long orderId = order.getId();
        //根据订单id获取所有的订单明细对象
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,orderId);
        List<OrderDetail> list = orderDetailService.list(queryWrapper);

        //循环遍历每一个订单明细对象，把他们转换成购物车对象
        List<ShoppingCart> shoppingCarts = list.stream().map((item) ->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setName(item.getName());
            shoppingCart.setNumber(item.getNumber());  //当前菜品或者套餐的份数
            shoppingCart.setDishFlavor(item.getDishFlavor());  //口味
            shoppingCart.setDishId(item.getDishId());
            shoppingCart.setSetmealId(item.getSetmealId());
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setAmount(item.getAmount());  //单份金额
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("再来一单...");
    }


    /**
     * 查询订单的分页信息，用于后端展示
     * @param page
     * @param pageSize
     * @param number  订单号
     * @param beginTime  开始日期
     * @param endTime  结束日期
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number,String beginTime,String endTime){
        //构造分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        Page<OrdersDto> ordersDtoPage=new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //根据订单号进行模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(number),Orders::getNumber,number);
        //根据Datetime进行时间范围查询
        if(beginTime!=null && endTime!=null){
            queryWrapper.ge(Orders::getOrderTime,beginTime);
            queryWrapper.le(Orders::getOrderTime,endTime);
        }
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //进行分页查询
        orderService.page(pageInfo,queryWrapper);

        //将分页对象的基本信息拷贝，除了‘records’
        BeanUtils.copyProperties(pageInfo,ordersDtoPage,"records");


        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list = records.stream().map((item)->{

            OrdersDto ordersDto=new OrdersDto();
            //将核心数据拷贝过去
            BeanUtils.copyProperties(item,ordersDto);
            //单独设置页面需要的用户名
            String name = "用户" + item.getUserId();
            ordersDto.setUserName(name);
            return ordersDto;
        }).collect(Collectors.toList());

        ordersDtoPage.setRecords(list);
        return R.success(ordersDtoPage);
    }

    /**
     * 后台派出/完成订单
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> editOrder(@RequestBody Orders orders){
        orderService.updateById(orders);
        return R.success("状态修改成功");
    }
}
